package com.ycsj.goldmedalnewconcept.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.ycsj.goldmedalnewconcept.activity.TeacherFansiListActivity.TeacherListAdapter;
import com.ycsj.goldmedalnewconcept.bean.AttResponse;
import com.ycsj.goldmedalnewconcept.bean.TeacherFansiResponse;
import com.ycsj.goldmedalnewconcept.bean.TeacherManageResponse;
import com.ycsj.goldmedalnewconcept.bean.TeacherFansiResponse.FansiContent;
import com.ycsj.goldmedalnewconcept.constant.Constant;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.R;

//我的反思
public class FansiActivity extends Activity implements OnClickListener {

	private ImageView iv_back;
	private String class_id;
	private String role;
	private String account;
	private String content;
	private String rowid = "-1";
	private String oldcontent = "-1";
	private int unit;
	private int lesson;
	private Intent intent;
	private EditText et_content;
	private TextView tv_save;
	private TextView tv_cancel;
	private List<FansiContent> list;
	private int y = -1;
	private String schoolId;

	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_fansi);
		intent = getIntent();
		unit = intent.getIntExtra("unit1", -1);
		lesson = intent.getIntExtra("lesson1", -1);
		class_id = intent.getStringExtra("class_id1");

		list = new ArrayList<FansiContent>();
		account = SPUtil.getString(this, "account", "");
		role = SPUtil.getString(this, "role", "");
		schoolId = SPUtil.getString(this, "schoolId", "");
		
		initView();
		setOnListener();
		initData();
	}

	private void initView() {
		// TODO Auto-generated method stub
		iv_back = (ImageView) findViewById(R.id.iv_back);
		et_content = (EditText) findViewById(R.id.et_content);
		tv_save = (TextView) findViewById(R.id.tv_save);
		tv_cancel = (TextView) findViewById(R.id.tv_cancel);
	}

	private void initData() {
		// TODO Auto-generated method stub

		OkHttpClient mOkHttpClient = new OkHttpClient();
		// mOkHttpClient.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		FormEncodingBuilder builder = new FormEncodingBuilder();
		builder.add("type", "22");
		builder.add("c", account);
		builder.add("role", role);
		builder.add("schoolid", schoolId);
		builder.add("userclass", class_id);
		// http://192.168.0.198:8888/ycsj_platform/ManageMsg?type=22&c=13006314760&role=2&userclass=1253
		Request request = new Request.Builder()
				.url(Constant.SERVER_LOC + "ManageMsg").post(builder.build())
				.build();
		mOkHttpClient.newCall(request).enqueue(new Callback() {

			@Override
			public void onFailure(Request arg0, IOException arg1) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						Toast.makeText(getBaseContext(), "网络无响应，请检查网络连接", 0)
								.show();
					}
				});
			}

			@Override
			public void onResponse(Response arg0) throws IOException {
				// 解析Json数据，保存登录状态及身份信息

				Gson gson = new Gson();

				String json = arg0.body().string();
				TeacherFansiResponse fromJson = gson.fromJson(json,
						TeacherFansiResponse.class);
				Log.e("test", json);
				if (fromJson != null) {
					if (!"-1".equals(fromJson.state)) {

						list = fromJson.list;
						String u = unit + "";
						String l = lesson + "";

						for (int i = 0; i < list.size(); i++) {

							if (u.equals(list.get(i).unit)
									&& l.equals(list.get(i).lesson)) {
								y = i;

							}
						}
						if (y != -1) {
							rowid = list.get(y).row_id;
							oldcontent = list.get(y).content;
							runOnUiThread(new Runnable() {
								@Override
								public void run() {
									et_content.setText(list.get(y).content);
								}
							});
						}
					}
				}
			}
		});
	}

	private void setOnListener() {
		// TODO Auto-generated method stub
		iv_back.setOnClickListener(this);
		tv_save.setOnClickListener(this);
		tv_cancel.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.iv_back:
			finish();
			break;
		case R.id.tv_cancel:
			finish();
			break;
		case R.id.tv_save:
			content = et_content.getText().toString().trim();
			if (!"-1".equals(rowid)) {
				if ("".equals(content)) {
					Toast.makeText(getBaseContext(), "内容不能为空，请输入内容后再进行保存", 0)
							.show();
					return;
				}
				if (oldcontent.equals(content) && content != "-1") {
					finish();
					return;
				}

				if (containsEmoji(content)) {
					Toast.makeText(this, "内容包含无法识别的表情字符，请重新编辑", 0).show();
				} else {
					modif();// 更新内容
				}
			} else {

				if (!"".equals(content)) {
					if (containsEmoji(content)) {
						Toast.makeText(this, "内容包含无法识别的表情字符，请重新编辑", 0).show();
					} else {
						save();// 新建内容
					}

				} else {
					Toast.makeText(getBaseContext(), "内容不能为空，请输入内容后再进行保存", 0)
							.show();
				}
			}
			break;
		}
	}

	private void modif() {
		OkHttpClient mOkHttpClient = new OkHttpClient();
		// mOkHttpClient.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		FormEncodingBuilder builder = new FormEncodingBuilder();
		builder.add("type", "20");
		builder.add("rowid", rowid);
		builder.add("c", account);
		builder.add("role", role);
		builder.add("content", content);

		Request request = new Request.Builder()
				.url(Constant.SERVER_LOC + "ManageMsg").post(builder.build())
				.build();
		mOkHttpClient.newCall(request).enqueue(new Callback() {

			@Override
			public void onFailure(Request arg0, IOException arg1) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						Toast.makeText(getBaseContext(), "网络无响应，请检查网络连接", 0)
								.show();
					}
				});
			}

			@Override
			public void onResponse(Response arg0) throws IOException {
				// 解析Json数据，保存登录状态及身份信息

				Gson gson = new Gson();

				String json = arg0.body().string();
				AttResponse fromJson = gson.fromJson(json, AttResponse.class);
				Log.e("test", json);
				if ("1".equals(fromJson.state)) {
					// 上传成功
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							Toast.makeText(getBaseContext(), "保存成功", 0).show();
						}
					});

					finish();
				} else {
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							Toast.makeText(getBaseContext(), "保存失败，请稍后重试", 0)
									.show();
						}
					});

				}
			}
		});
	}

	public boolean containsEmoji(String source) {
		int len = source.length();
		for (int i = 0; i < len; i++) {
			char codePoint = source.charAt(i);
			if (!isEmojiCharacter(codePoint)) { // 如果不能匹配,则该字符是Emoji表情
				return true;
			}
		}
		return false;
	}

	private boolean isEmojiCharacter(char codePoint) {
		return (codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA)
				|| (codePoint == 0xD)
				|| ((codePoint >= 0x20) && (codePoint <= 0xD7FF))
				|| ((codePoint >= 0xE000) && (codePoint <= 0xFFFD))
				|| ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF));
	}

	private void save() {
		OkHttpClient mOkHttpClient = new OkHttpClient();
		// mOkHttpClient.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		FormEncodingBuilder builder = new FormEncodingBuilder();
		builder.add("type", "19");
		builder.add("c", account);
		builder.add("role", role);
		builder.add("schoolid", "");
		builder.add("userclass", class_id);
		builder.add("unit", unit + "");
		builder.add("lesson", lesson + "");
		builder.add("content", content);

		Request request = new Request.Builder()
				.url(Constant.SERVER_LOC + "ManageMsg").post(builder.build())
				.build();
		mOkHttpClient.newCall(request).enqueue(new Callback() {

			@Override
			public void onFailure(Request arg0, IOException arg1) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						Toast.makeText(getBaseContext(), "网络无响应，请检查网络连接", 0)
								.show();
					}
				});
			}

			@Override
			public void onResponse(Response arg0) throws IOException {
				// 解析Json数据，保存登录状态及身份信息

				Gson gson = new Gson();

				String json = arg0.body().string();
				AttResponse fromJson = gson.fromJson(json, AttResponse.class);
				Log.e("test11", json);
				if ("1".equals(fromJson.state)) {
					// 上传成功
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							Toast.makeText(getBaseContext(), "保存成功", 0).show();
						}
					});

					finish();
				} else {
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							Toast.makeText(getBaseContext(), "保存失败，请稍后重试", 0)
									.show();
						}
					});

				}
			}
		});
	}
}
